package com.zhilianbao.leyaogo.view.widgets;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * 宽度充满屏幕，高度自适应
 * Created by gyt on 2017/1/9
 */
public class RatioImageView extends ImageView {
    public RatioImageView(Context context) {
        super(context);
    }

    public RatioImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RatioImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Drawable drawable = getDrawable();
        if (drawable != null) {
            float ratio = (float) drawable.getIntrinsicHeight() / (float) drawable.getIntrinsicWidth();
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = (int) (width * ratio);
            setMeasuredDimension(width, height);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}
